﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

public partial class Search : System.Web.UI.Page
{
    string sQuery;
    string sTag;
    protected int iItemsFound = 0;
    protected int iCurrentPage;
    private int iPageSize=12;
    private int iTotalPages;
    DataTable DT;

    protected void Page_Load(object sender, EventArgs e)
    {
        GetParameters();

        #region Search by query
        if (sQuery.Length > 0)
        {
            Page.Title += sQuery;
            Dal.arParams.Clear();
            Dal.arParams.Add("\""+sQuery.Replace("\"","\"\"")+"\"");
            Dal.arParams.Add(iCurrentPage);
            Dal.arParams.Add(iPageSize);
            DT = Dal.ExecuteDBsp("usp_GetSearchResult", Dal.arParams, true);


            if (DT != null)
                if (DT.Rows.Count > 0)
                {
                    iItemsFound = Convert.ToInt32(DT.Rows[0]["totalrows"]);
                    iTotalPages = (int)Math.Ceiling((double)iItemsFound / iPageSize);

                    foreach (DataRow DR in DT.Rows)
                    {
                        string sStart = string.Empty;
                        string sEnd = string.Empty;
                        string sText = StripHtml(DR["Article"].ToString());

                        Int32 iqueryStarts = sText.IndexOf(sQuery, 0);

                        if (iqueryStarts > -1)
                        {
                            if (sText.Substring(iqueryStarts).Length > 115)
                            {
                                sEnd = sText.Substring(iqueryStarts, 115);
                                sEnd = sEnd.Remove(sEnd.LastIndexOf(" "));
                                sEnd += "...";
                            }
                            else
                                sEnd = sText.Substring(iqueryStarts);
                            if (iqueryStarts > 115)
                            {
                                sStart = sText.Substring(iqueryStarts - 115, 115);
                                sStart = sStart.Remove(0, sStart.IndexOf(" "));
                                sStart = sStart.Insert(0, "...");
                            }
                            else
                            {
                                sStart = sText.Substring(0, iqueryStarts);
                            }

                            sEnd = sEnd.Replace(sQuery, string.Format("<span>{0}</span>", sQuery));
                            DR["Article"] = sStart + sEnd;
                        }
                        else
                        {
                            sText = StripHtml(DR["cTitle"].ToString());
                            sText.Replace(sQuery, string.Format("<span>{0}</span>", sQuery));

                            DR["ctitle"] = sText;
                            string sArticle = DR["Article"].ToString().Substring(0,230);
                            sArticle = sArticle.Remove(sArticle.LastIndexOf(" "));
                            sArticle += "...";
                            DR["Article"] = sArticle;
                        }
                    }

                    gvNews.DataSource = DT;
                    gvNews.DataBind();
                    
                    if (iTotalPages > 1)
                        SimplePager();
                }
        }
        #endregion

        #region Search by tag
        if (sTag.Length > 0)
        {
            Page.Title += sTag;
            Dal.arParams.Clear();
            Dal.arParams.Add(sTag);
            Dal.arParams.Add(iCurrentPage);
            Dal.arParams.Add(iPageSize);
            DT = Dal.ExecuteDBsp("usp_GetSearchByTag", Dal.arParams, true);


            if (DT != null)
                if (DT.Rows.Count > 0)
                {
                    iItemsFound = Convert.ToInt32(DT.Rows[0]["totalrows"]);
                    iTotalPages = (int)Math.Ceiling((double)iItemsFound / iPageSize);

                    foreach (DataRow DR in DT.Rows)
                    {
                       
                        DR["Article"] = DR["SubTitle"];
                    }

                    gvNews.DataSource = DT;
                    gvNews.DataBind();

                    if(iTotalPages>1)
                        SimplePager();
                }
        }
        #endregion
    }


    public void SimplePager()
    {
        if (iCurrentPage < 0) iCurrentPage = 1;
        if (iTotalPages < 0) iTotalPages = 0;
        PagerBuilder pager = null;
        if(sQuery.Trim().Length>0)
            pager = new PagerBuilder(sQuery,true);
        else
            pager = new PagerBuilder(sTag,false);

        if (iCurrentPage > 1)
        {
            pager.AddPage("&lt;&lt;", 1);
            pager.AddPage("&lt;", iCurrentPage-1);
        }

        var start = Math.Max(iCurrentPage - 2, 1);
        var end = Math.Min(iTotalPages, iCurrentPage + 2);

        for (var i = start; i <= end; i++)
        {
            if (i == iCurrentPage)
                pager.AddPage(i.ToString(), i, "font-weight: bold; color: #0b61a4;");
            else
                pager.AddPage(i.ToString(), i);
        }

        if (iCurrentPage < iTotalPages)
        {
            pager.AddPage("&gt;", iCurrentPage + 1);
            pager.AddPage("&gt;&gt;", iTotalPages);
        }

        nav6.InnerHtml += pager.ToString();
    }

    private string StripHtml(string html)
    {
        if (html == null || html == string.Empty)
            return string.Empty;

        String sRetString = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]*>", string.Empty);
        sRetString = sRetString.Replace("&nbsp;", "");
        return sRetString;
    }

    private void GetParameters()
    {
        sQuery = (Request.Params["q"] != null) ? Request.Params["q"].ToString() : string.Empty;
        sQuery = HttpUtility.UrlDecode(sQuery);
        sTag = (Request.Params["t"] != null) ? Request.Params["t"].ToString() : string.Empty;
        iCurrentPage = Convert.ToInt32(Request.Params["page"]);
    }

    protected void gvNews_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        int iArticleID = Convert.ToInt32(((HiddenField)e.Item.FindControl("hfID")).Value);

        HyperLink lnkArticle=((HyperLink)e.Item.FindControl("lnkArticle"));

        DataRow DR = DT.Select("ArticleID=" + iArticleID)[0];

        string  sLink=DR["cPageName"].ToString();

        NewsType newsType;
        
        int iAncestorID=Convert.ToInt32(DR["ancestorID"]);
        newsType = (NewsType)Convert.ToInt32(DT.Select("ArticleID=" + iArticleID)[0]["CatID"]);

        switch(iAncestorID)
        {
            case 3:
                newsType = NewsType.Wiki;
                break;
            case 4:
                newsType = NewsType.MedicalCenters;
                break;
            case 8:
                newsType = NewsType.hotels;
                break;
            default:
            int iPID = Convert.ToInt32(DR["PID"]);
            if (iPID == 3)
                newsType = NewsType.Wiki;
            break;
        }

        
        switch(newsType)
        {
            case NewsType.news:
            case NewsType.popular:
                lnkArticle.NavigateUrl = string.Format("{0}-a.aspx", sLink);
                break;
            case NewsType.deadSea:
                lnkArticle.NavigateUrl = string.Format("deadsea.aspx");
                break;
            case NewsType.aboutUS:
                lnkArticle.NavigateUrl = string.Format("about.aspx");
                break;
            case NewsType.Wiki:
                lnkArticle.NavigateUrl = string.Format("{0}-wa.aspx", sLink);
                break;
            case NewsType.MedicalCenters:
                lnkArticle.NavigateUrl = string.Format("{0}-ca.aspx", sLink);
                break;
            case NewsType.hotels:
                lnkArticle.NavigateUrl = string.Format("{0}-a.aspx", sLink);
                break;
            case NewsType.MedicalTourism:
                lnkArticle.NavigateUrl = string.Format("{0}-a.aspx", sLink);
                break;
        }
        DataList dlTags = ((DataList)e.Item.FindControl("rptTags"));

        Dal.arParams.Clear();
        Dal.arParams.Add(iArticleID);
        DataTable DTTags = Dal.ExecuteDBsp("usp_GetTagsByArticleID", Dal.arParams);
        if (DTTags != null)
            if (DTTags.Rows.Count > 0)
            {
                dlTags.DataSource = DTTags;
                dlTags.DataBind();
            }
            else
                e.Item.FindControl("divTags").Visible = false;
    }

    public class PagerBuilder
    {
        private class PagerLink
        {
            public string Title { get; set; }
            public int PageNo { get; set; }
            public string Class { get; set; }
        }

        private readonly string _urlTemplate;
        private readonly List<PagerLink> _pagerLinks =
                new List<PagerLink>();
        private bool isQuerry;

        public PagerBuilder(string urlTemplate,bool isQuerry)
        {
            this.isQuerry = isQuerry;

            _urlTemplate = urlTemplate;
        }

        public string PagerClass { get; set; }

        public void AddPage(string title, int pageNo)
        {
            AddPage(title, pageNo, string.Empty);
        }

        public void AddPage(string title, int pageNo,
                            string itemClass)
        {
            var link = new PagerLink
            {
                PageNo = pageNo,
                Title = title,
                Class = itemClass
            };
            _pagerLinks.Add(link);
        }

        public override string ToString()
        {
            var builder = new StringBuilder();

            foreach (var link in _pagerLinks)
            {
                builder.Append("<li>");
                builder.Append("<a");
                if (link.Class != string.Empty)
                {
                    builder.AppendFormat(" style=\"{0}\"", link.Class);
                }
                builder.Append(" href=\"");
                if(isQuerry)
                    builder.AppendFormat("search.aspx?q={0}&page={1}", _urlTemplate, link.PageNo);
                else
                    builder.AppendFormat("search.aspx?t={0}&page={1}", _urlTemplate, link.PageNo);
                builder.Append("\">");
                builder.Append(link.Title);
                builder.Append("</a>");
                builder.Append("</li>");
            }
            return builder.ToString();
        }
    }
}
